package com.um.jdy.mp.merchant.manager;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.um.jdy.common.baofu.entity.po.BaofuUser;
import com.um.jdy.common.baofu.service.BaofuService;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.finance.enums.FinancialEnum;
import com.um.jdy.common.platform.code.PartnersCode;
import com.um.jdy.common.platform.entity.dto.MerchantDTO;
import com.um.jdy.common.platform.entity.po.Merchant;
import com.um.jdy.common.platform.enums.PlatformEnum;
import com.um.jdy.common.platform.service.MerchantService;
import com.um.jdy.mp.merchant.entity.dto.EditMerchantDTO;
import com.um.jdy.mp.user.entity.vo.MerchantVO;
import com.um.jdy.mp.user.service.SessionUserService;
import com.um.springboot.starter.code.CommonCode;
import com.um.springboot.starter.entity.Page;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.springboot.starter.orm.params.PageParams;
import com.um.springboot.starter.utils.DesEncrypter;
import com.um.springboot.starter.utils.RSAUtil;
import com.um.springboot.starter.utils.StringUtil;
import com.um.springboot.starter.utils.UMBeanUtils;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 管理类：平台商家表
 */
@Component
public class MerchantManager extends BaseManager<MerchantService> {

    @Autowired
    SessionUserService sessionUserService;
    @Autowired
    BaofuService baofuService;

    /**
     * 查询分页
     *
     * @param params
     * @return
     */
    public Response<Page<MerchantVO>> page(PageParams params) {
        Page<MerchantVO> page = new Page();
        page.setPageNo(params.getPageNo());
        page.setPageSize(params.getPageSize());
        params.getCondition().put("m.com_id", getComId());
        params.getCondition().put("m.parent_id", sessionUserService.getTokenUserId());
        page = service.getCMSViewModelPageBySqlName(page, "get_merchant_page", "get_merchant_count", MerchantVO.class,
                params.getProperties(), params.getValues(), params.getRangeEntitys(), params.getOrderNames(), params.getSortOns());
        return Response.success(page);
    }

    /**
     * 查询下级列表
     * @param name
     * @return
     */
    public Response<List<MerchantVO>> list(String type,String name) {
        List<Merchant> list = service.getListByLike(new String[]{"com_id","parent_id","name","type"},new Object[]{getComId(),sessionUserService.getTokenUserId(),StringUtil.getQueryParam(name),type},new String[]{"create_time"},new String[]{"desc"});
        return Response.success(UMBeanUtils.copyBeanList(list,MerchantVO.class));
    }

    @Transactional
    public Response<MerchantVO> addEntity(MerchantDTO dto) {

        if (service.getEntity("mobile", dto.getMobile()) != null) {
            return Response.failed(PartnersCode.MobileExist);
        }

        if(sessionUserService.getTokenUser().getCommissionRate() < dto.getCommissionRate()) {
            PartnersCode partnersCode = PartnersCode.RateNotLargeThanParent;

            if(sessionUserService.getTokenUser().getType().equals("merchant")) {
                partnersCode = PartnersCode.RateNotLargeThanParentMerchant;
            }

            throw new ServiceException(partnersCode);
        }

        dto.setParentId(sessionUserService.getTokenUserId());
        Merchant entity = UMBeanUtils.copyBean(dto, Merchant.class);
        if(entity.getLevel() == null) {
            entity.setLevel(0);
        }
        if (entity.getType().equals("merchant")) {
            if (StringUtil.getTrim(entity.getParentId()).equals("")) {
                entity.setLevel(1);
            } else {
                entity.setLevel(2);
            }
        }

        if (entity.getLevel() == 2){
            if (sessionUserService.getTokenUser().getCommissionRate() < dto.getCommissionRate()) {
                throw new ServiceException(PartnersCode.RateNotLargeThanParent);
            }
        }

        //宝付用户验证
        if(StrUtil.isBlank(dto.getBaofuUserId())){
            throw new ServiceException(PartnersCode.BaofuNotExist);
        }
        BaofuUser baofuUser = baofuService.getEntity(dto.getBaofuUserId());
        if(baofuUser == null){
            throw new ServiceException(PartnersCode.BaofuNotExist);
        }

        String pwd = RSAUtil.simpleDecrypt(dto.getPassword());
        DesEncrypter des = new DesEncrypter(DesEncrypter.CD_KEY);
        String encryptPwd = des.encrypt(pwd);

        entity.setPassword(encryptPwd);
        entity.setIsEnable(YesOrNo.Yes.name());
        entity.setCashoutAuditType(FinancialEnum.CashoutAuditType.Artificial.name());
        entity.setCreateTime(new Date());
        service.addEntity(entity);

        return Response.success(BeanUtil.toBean(entity, MerchantVO.class));
    }

    @Transactional
    public Response<MerchantVO> updateEntity(String id, EditMerchantDTO dto) {

        checkPermission(id);

        if(sessionUserService.getTokenUser().getCommissionRate() < dto.getCommissionRate()) {
            PartnersCode partnersCode = PartnersCode.RateNotLargeThanParent;
            if(sessionUserService.getTokenUser().getType().equals("merchant")) {
                partnersCode = PartnersCode.RateNotLargeThanParentMerchant;
            }
            throw new ServiceException(partnersCode);
        }

        List<Merchant> list = service.getList("parent_id", id);

        int rate = 0;
        for (Merchant item : list) {
            rate = Math.max(rate, item.getCommissionRate());
        }

        if (dto.getCommissionRate() < rate) {
            throw new ServiceException(PartnersCode.RateNotLessThanChild);
        }

        Merchant entity = service.getEntity(id);
        BeanUtils.copyProperties(dto, entity);
        this.service.updateEntity(entity);
        return Response.success(BeanUtil.toBean(entity, MerchantVO.class));
    }

    public Response<MerchantVO> get(String id){

        checkPermission(id);

        Merchant entity = service.getEntity(id);
        return Response.success(BeanUtil.toBean(entity, MerchantVO.class));
    }

    /**
     * 校验数据权限
     * @param id
     */
    private void checkPermission(String id){
        Merchant merchant = service.getEntity(id);
        if(merchant == null)
            throw new ServiceException(PartnersCode.PartnersNotExist);

        if(!StringUtil.equals(sessionUserService.getTokenUserId(),merchant.getParentId()))
            throw new ServiceException(CommonCode.NoDataPermission);
    }

}
